;
//报警设置
(function () {
    var main = {
        baseUrl: CafeJS.CXT,
        mapId: "tjMap",
        userInfo: null,
        areaExent: {
            12: [114.94, 38.32, 119.80, 40.47], // 全市
            120110: [117.23, 39.25, 117.56, 39.01], // 东丽区
            120111: [116.87, 39.17, 117.34, 38.83], // 西青区
            120112: [117.22, 39.08, 117.54, 38.84], // 津南区
            120113: [116.95, 39.35, 117.40, 39.18], // 北辰区
            120114: [116.79, 39.70, 117.34, 39.15], // 武清区
            120115: [117.14, 39.83, 117.69, 39.38], // 宝坻区
            120116: [117.15, 39.29, 118.03, 38.57], // 滨海新区
            120221: [117.31, 39.60, 117.94, 39.18], // 宁河区
            120223: [116.70, 39.08, 117.24, 38.62], // 静海区
            120125: [117.14, 40.25, 117.78, 39.78], // 蓟州区
            2: [108.71, 43.88, 123.66, 35.55], // 海河流域
            1: [108.71, 43.88, 123.66, 35.55], // 黄渤海
            4: [117.05, 39.24, 117.35, 39.01]//市区
        },
        router: {
            // getSkPmData: 'zhfx/station/list/queryOneElementTJ',
            getSkPmData: 'shortWarn/autoStation/queryTopAutoStationData'
        },
        areaCfg: {
            1: '黄渤海', 2: '海河', 12: '天津', 4: '市区', 120225: '蓟州', 120115: '宝坻', 120221: '宁河', 120113: '北辰',
            120116: '滨海新区', 120114: '武清', 120111: '西青', 120110: '东丽', 120223: '静海', 120112: '津南'
        },
        elementCfg: {
            'RAIN': { name: '降水', time: { 1: '1小时', 3: '3小时', 6: '6小时', 12: '12小时', 24: '24小时' }, thead: ['序号', '站号', '站名', '累计降水量（mm）'], unit: 'mm' },
            'T_MAX': { name: '高温', time: { 0: '实时', 6: '6小时', 12: '12小时', 24: '24小时' }, thead: ['序号', '站号', '站名', '最高温（℃）', '出现时间'], unit: '℃' },
            'T_MIN': { name: '低温', time: { 0: '实时', 6: '6小时', 12: '12小时', 24: '24小时' }, thead: ['序号', '站号', '站名', '最低温（℃）', '出现时间'], unit: '℃' },
            'WS_10M': { name: '10分钟风', time: { 1: '1小时', 3: '3小时', 6: '6小时', 12: '12小时', 24: '24小时' }, thead: ['序号', '站号', '站名', '10分钟风（m/s）', '出现时间'], unit: 'm/s' },
            'WS_EXT': { name: '极大风', time: { 1: '1小时', 3: '3小时', 6: '6小时', 12: '12小时', 24: '24小时' }, thead: ['序号', '站号', '站名', '极大风（m/s）', '出现时间'], unit: 'm/s' },
            'RH_MIN': { name: '湿度', time: { 0: '实时', 6: '6小时最小', 12: '12小时最小', 24: '24小时最小' }, thead: ['序号', '站号', '站名', '湿度（%）', '出现时间'], unit: '%' },
            'VIS_10M': { name: '能见度', time: { 0: '实时', 3: '3小时最小', 6: '6小时最小', 12: '12小时最小', 24: '24小时最小' }, thead: ['序号', '站号', '站名', '能见度（m）', '出现时间'], unit: 'm' },
            'MAX_TP': { name: '最大雨强', time: { 0: '实时', 3: '3小时最小', 6: '6小时最小', 12: '12小时最小', 24: '24小时最小' }, thead: ['序号', '站号', '站名', '最大雨强（mm）', '出现时间'], unit: 'mm' }
        },
        siteTypeCfg: { '基本站': '0', '区域站': '1', '海岛站': '2', '浮标站': '3', '船舶站': '4', '平台站': '5' },
        skTime: '',
        startDatePicker:null,
        endDatePicker:null,
        init: function () {
            var userInfo = $("#userInfo").data('info');
            this.userInfo = userInfo;
            $("#siteTypeSelect").fSelect();
            this.initArea();
            this.initElement();
            this.initWarnTip();
            this.bindEvt();
        },
        // 初始化区域
        initArea: function () {
            var that = this;
            var $area = $("#area");
            for (var key in that.areaCfg) {
                var code = that.userInfo.userAreaCode;
                code = '12'
                if (code == key) {
                    $area.append(`<option selected value="${key}">${that.areaCfg[key]}</option>`)
                } else {
                    $area.append(`<option value="${key}">${that.areaCfg[key]}</option>`)
                }
            }
        },
        // 初始化要素
        initElement: function () {
            var that = this;
            var $element = $("#element");
            for (var key in that.elementCfg) {
                var $option = $(`<option value="${key}">${that.elementCfg[key].name}</option>`);
                $element.append($option);
            }
        },
        // 初始化报警排名数据
        initWarnTip: function () {
            var that = this;
            var skTime = $("#datepicker-autostat .datepicker-date span").text()
            if (!skTime) {
                skTime = $('#latestTime').val();
            }
            $(".ranking-head span").html(new Date(skTime).format('yyyyMMdd hhmm'));
            var areaCode = $('#area option:selected').val();
            var hours = $('.agings>div>span.active').attr('hours')
            if ($("#startTime").val()) {
                hours = $("#startTime").val();
            }
            if ($("#startTime").val() > 24) {
                alert('查询范围过长，请前往统计查询模块');
                return;
            }
            var startTime = new Date(skTime);
			if (Number(hours) === 0) {
				startTime.setMinutes(startTime.getMinutes() - 1);
			} else {
				startTime.setHours(startTime.getHours() - hours);
			}
            startTime = startTime.format('yyyy-MM-dd hh:mm:ss');
            var stationTypes = [];
            var stationVal = $('.fs-label').html();
            stationVal.split(',').forEach(function (item) {
                stationTypes.push(that.siteTypeCfg[item]);
            })
            
            var param = {
                element: $("#element").val(),
                areaCode: areaCode,
                startTime: startTime,
                endTime: skTime+ ':00',
                stationTypes: stationTypes.join(',')
            }
            debugger
            if("MAX_TP" == $("#element").val()){
                param.startTime = new Date(that.startDatePicker.getVal()+":00").format('yyyy-MM-dd hh:00:00');
                param.endTime = new Date(that.endDatePicker.getVal()+":00").format('yyyy-MM-dd hh:00:00');
            }
            $.getJSON(that.router.getSkPmData, param, function (res) {
                if (res.isSuccess || res.data) {
                    that.dataArr = res.data;
                    that.buildTable();
                };
            })
        },
        // 展示表格
        buildTable: function () {
            var that = this;
            var $body = $(".ranking-table table tbody").empty();
            var element = $("#element").val()
            for (var i = 0; i < that.dataArr.length; i++) {
                var proObj = that.dataArr[i];
                // if( "MAX_TP" == element){
                //     proObj.time = proObj.bjdatetime;
                // }
                // var time = proObj.time
                // if (!time) {
                //     time = ''
                // } else if (time.toString().length > 5) {
                //     time = new Date(time).format('yyyy-MM-dd hh:mm:ss')
                // } else {
				// 	var hour = Number(proObj.time.substr(0, proObj.time.length - 2));
				// 	hour += 8;
				// 	proObj.time = hour + '' + proObj.time.substr(proObj.time.length - 2, proObj.time.length);
                //     time = proObj.time;
                // }
                var number = i + 1
                var tr = '<tr><td>' + number + '</td>'
                tr += '<td>' + proObj.stationId + '</td>'
                tr += '<td>' + proObj.stationName + '</td>'
                tr += '<td>' + proObj.VAL + that.elementCfg[element].unit + '</td>'
                if (element != 'RAIN') {
                    tr += '<td title="' + proObj.time + '">' + proObj.time + '</td>'
                }
                var $tr = $(tr);
                $tr.data('list', proObj);
                $body.append($tr);
            }
        },
        // 表格排序
        sortTable: function (obj, ele) {
            if (obj.hasClass("asc")) {
                this.dataArr.sort(function (i, j) { return i[ele] - j[ele] });
                obj.removeClass("asc").addClass("desc")
            } else if (obj.hasClass("desc")) {
                this.dataArr.sort(function (i, j) { return j[ele] - i[ele] });
                obj.removeClass("desc").addClass("asc")
            }
            this.buildTable();
        },
        initTableHead: function (thead) {
            var $thead = $(".ranking-table table thead tr").empty();
            var $body = $(".ranking-table table tbody").empty();
            thead.forEach(function (item) {
                $thead.append(`<th>${item}</th>`);
            })
            $(".ranking-table table thead tr th:nth-child(4)").addClass('asc').attr('id', 'score');
        },
        bindEvt: function () {
            var that = this;
            $(".ranking-head i").click(function () {
                $(".ranking-main").toggleClass("none");
                $(this).toggleClass("transform");
            }).mousedown(function (e) {
                event.stopPropagation();
            });
            $(".agings").on('click', 'div>span', function () {
                $(this).addClass("active").siblings().removeClass("active");
            })
            $("#area").change(function () {
                var val = Number($(this).val());
                GIS.Extent.Set(that.mapId, { xmin: that.areaExent[val || 12][0], xmax: that.areaExent[val || 12][2], ymax: that.areaExent[val || 12][1], ymin: that.areaExent[val || 12][3] });
            })
            $("#element").change(function () {
                $(this).find("option").each(function () {
                    if ($(this).prop("selected")) {
                        var $agings = $(".agings").empty()
                        var val = $(this).val();
                        var thead = that.elementCfg[val].thead
                        that.initTableHead(thead)
                        if(val == "MAX_TP"){
                            var skTime = $("#datepicker-autostat .datepicker-date span").text()
                            if (!skTime) {
                                skTime = $('#latestTime').val();
                            }
                            var startTime = new Date(skTime);
                            startTime.setHours(startTime.getHours() - 24);
                            var $div = $("<div>");
                            $div.append($("<div>").text("开始时间:").css({
                                'margin': '5px 5px 0px 5px',
                                'float': 'left',
                                'display': 'inline-block',
                            }));
                            $div.append($("<div>").attr("id","startTimeDatePicker"));
                            
                            $div.append($("<div>").text("结束时间:").css({
                                'margin': '5px 5px 0px 5px',
                                'float': 'left',
                                'display': 'inline-block',
                            }));
                            $div.append($("<div>").attr("id","endTimeDatePicker"));
                             $agings.append($div);
                             that.startDatePicker = CafeJS.Datepicker({
                                appendTo: "#startTimeDatePicker",
                                curDate: startTime.format('yyyy-MM-dd hh:00:00'),
                                type: 1,
                                timeInterval: 60,
                            });
                            that.endDatePicker = CafeJS.Datepicker({
                                appendTo: "#endTimeDatePicker",
                                curDate: new Date(skTime).format('yyyy-MM-dd hh:00:00'),
                                type: 1,
                                timeInterval: 60,
                            });
                        }else{
                            var time = that.elementCfg[val].time
                            var div = '<div>'
                            for (var key in time) {
                                div += '<span hours="' + key + '">' + time[key] + '</span>';
                            }
                            div += '<div><span>自定义 </span><input type="text" id="startTime"></div>'
                            $agings.append(div);
                        }
                        
                    }
                    $(".agings>div>span:first-child").click();
                })
            })
            $("#queryBtn").click(function () {
                that.initWarnTip()
            })
            $('.ranking-table table thead tr').on('click', '#score', function () {
                that.sortTable($(this), 'VAL');
            });
            $(".agings").on('keyup', 'input', function () {
                $(this).val($(this).val().replace(/[^\-?\d]/g, ''));
            })
            $(".ranking-head i").click();
        }
    }
    main.init();
})()
